# 创建一个蓝图(Blueprint)对象
import sqlalchemy.exc
from flask import Blueprint, request

from Model.models import Caregiver, db
from Utils.APIResponse import APIResponse

caregiver_blue = Blueprint("caregiver", __name__)


@caregiver_blue.route('/caregiver/create', methods=['POST'])
def create_caregiver():
    data = request.json
    name = data.get('name')
    contact_info = data.get('contact_info')
    experience = data.get('experience')

    if not all([name, contact_info, experience]):
        return APIResponse.error({'error': 'All fields are required.'})

    new_caregiver = Caregiver(name=name, contact_info=contact_info, experience=experience)
    db.session.add(new_caregiver)
    try:
        db.session.commit()
        return APIResponse.success(message={'message': 'Caregiver created successfully.'},
                                   data={'id': new_caregiver.id})
    except sqlalchemy.exc.SQLAlchemyError as e:
        db.session.rollback()
        return APIResponse.error({'error': 'Error creating caregiver: ' + str(e)}, status_code=500)


@caregiver_blue.route('/caregiver/list', methods=['GET'])
def list_caregivers():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    caregivers = Caregiver.query.paginate(page=page, per_page=per_page, error_out=False)
    data = [{'id': caregiver.id, 'name': caregiver.name, 'contact_info': caregiver.contact_info,
             'experience': caregiver.experience} for caregiver in caregivers.items]
    return APIResponse.success(data=data)


@caregiver_blue.route('/caregiver/update/<int:caregiver_id>', methods=['PUT'])
def update_caregiver(caregiver_id):
    caregiver = Caregiver.query.get(caregiver_id)
    if not caregiver:
        return APIResponse.error({'error': 'Caregiver not found.'}, status_code=404)

    data = request.json
    caregiver.name = data.get('name', caregiver.name)
    caregiver.contact_info = data.get('contact_info', caregiver.contact_info)
    caregiver.experience = data.get('experience', caregiver.experience)

    try:
        db.session.commit()
        return APIResponse.success(message={'message': 'Caregiver updated successfully.'})
    except sqlalchemy.exc.SQLAlchemyError as e:
        db.session.rollback()
        return APIResponse.error({'error': 'Error updating caregiver: ' + str(e)}, status_code=500)


@caregiver_blue.route('/caregiver/delete/<int:caregiver_id>', methods=['DELETE'])
def delete_caregiver(caregiver_id):
    caregiver = Caregiver.query.get(caregiver_id)
    if not caregiver:
        return APIResponse.error({'error': 'Caregiver not found.'}, status_code=404)

    db.session.delete(caregiver)
    try:
        db.session.commit()
        return APIResponse.success(message={'message': 'Caregiver deleted successfully.'})
    except sqlalchemy.exc.SQLAlchemyError as e:
        db.session.rollback()
        return APIResponse.error({'error': 'Error deleting caregiver: ' + str(e)}, status_code=500)
